package unit;

import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 远程调用接口类
 *
 * @Authority 梁昊
 * @Date 2020-02-26
 */
public final class RemoteInterFaceClass {
    /**
     * 远程接口前缀
     */
    private String remoteUrlFront;
    private String remoteUrlLog;
    private OkHttpClient okHttpClient;

    public void setRemoteUrlFront(String remoteUrlFront) {
        this.remoteUrlFront = remoteUrlFront;
    }

    public RemoteInterFaceClass(String remoteUrlFront, String remoteUrlLog) {
        this.remoteUrlFront = remoteUrlFront;
        this.remoteUrlLog = remoteUrlLog;
    }

    public String getLog(String methodUrl) throws IOException {
        String url = String.format("%s%s"
                , this.remoteUrlLog
                , methodUrl);
        return syncOkHttp(url, "POST");
    }
    public String getDoorParamList(String methodUrl) throws IOException {
        String url = String.format("%s%s"
                , this.remoteUrlFront
                , methodUrl);
        return syncOkHttp(url, "POST");
    }
    public String getDoorMessageList(String methodUrl) throws IOException {
        String url = String.format("%s%s"
                , this.remoteUrlFront
                , methodUrl);
        return syncOkHttp(url, "POST");
    }

    /**
     * 同步请求
     *
     * @param url
     * @return
     * @throws IOException
     */
    private String syncOkHttp(String url, String methodType) throws IOException {

        okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();

        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url(url)
                .method(methodType, body)
                .addHeader("Accept-Encoding", "UTF-8")
                .addHeader("Accept-Charset", "application/json")
                .addHeader("Content-Type","application/x-www-form-urlencoded")
                .addHeader("Cache-Control","no-cache")
                .addHeader("Accept","*/*")
                .addHeader("Content-Length","0")
                .addHeader("Connection","keep-alive")
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if (!response.isSuccessful() && response.code() == 401)
            throw new IOException("Unexpected code " + response);

        return response.body().string();
    }

    public String getRemoteUrlLog() {
        return remoteUrlLog;
    }

    public void setRemoteUrlLog(String remoteUrlLog) {
        this.remoteUrlLog = remoteUrlLog;
    }
}
